<template>


  <el-dialog
      top="20px"
      :title="defaultValue.title"
      :lock-scroll="tableConfig.lockScroll"
      :append-to-body="tableConfig.appendToBody"
      :visible="tableConfig.show"
      @close="tableConfig.show = false"
      :show-close="tableConfig.close"
      :destroy-on-close="tableConfig.destroyOnClose"
      width="1100px">

    <el-form size="small" ref="formOpsComponentRef" :rules="checkRule" :model="submitData" label-width="180px">

      <el-form-item label="组件图标" prop="ico">
        <SingleImageAsyncUpload ref="componentRef" imageTypePath="component" objectType="1"/>
      </el-form-item>

      <el-form-item label="组件名称" prop="name">
        <el-input v-model.trim="submitData.name" />
      </el-form-item>

      <el-form-item label="运行环境" prop="os">
        <el-select v-model="submitData.osList" placeholder="请选择" clearable multiple>
          <el-option
            v-for="item in osOpt"
            :key="item.key"
            :label="item.value"
            :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="组件介绍" prop="briefIntroduction">
        <el-input v-model="submitData.briefIntroduction" type="textarea" :autosize="{minRows: 3}" />
      </el-form-item>

      <el-form-item label="官网地址" prop="officialWebUrl">
        <el-input v-model.trim="submitData.officialWebUrl" />
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd"
                 v-if="defaultValue.saveUpdSelect !== 'select'">{{ defaultValue.title }}</el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>


</template>

<script>

import http from '@/utils/http'
import {clearInvalid, checkNull} from "@/utils/utils"
import SingleImageAsyncUpload from '@/components/common/SingleImageAsyncUpload.vue';


export default {
  name: "OpsComponentSaveUpd",
  components: {
    SingleImageAsyncUpload
  },
  data() {
    return {
      // 表格的默认值
      tableConfig: {
        // 关闭时销毁 Dialog 中的元素
        destroyOnClose: true,
        // 弹出框是否打开
        show: false,
        // 是否显示关闭按钮
        close: true,
        // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
        lockScroll: false,
        appendToBody: true,
      },
      // 默认值，进入页面后的值
      defaultValue: {
        // 弹出框标题
        title: '查看',
        // 保存还是修改or查看,取值有 select | save | upd
        saveUpdSelect: 'select'
      },
      // 提交的数据
      submitData:{
        name: null,
        os: null,
        briefIntroduction: null,
        ico: null,
        officialWebUrl: null,
      },
      // 校验规则
      checkRule: {
        name: [{required: true, message: '请输入组件名称', trigger: 'blur'}],
        briefIntroduction: [{required: true, message: '请输入组件名称', trigger: 'blur'}],
      },
      // 支持的运行环境
      osOpt:[
        {key: 1, value: 'LINUX'},
        {key: 2, value: 'WINDOWS'},
        {key: 3, value: 'MAC'},
        {key: 4, value: 'UNIX'},
      ],
    }
  },
  methods: {
    /**
     * 初始化操作
     * @param operateType 操作类型,保存还是修改or查看,取值有 select \ save \ upd
     * @param obj 如果是修改和查看，则是详细数据,需要赋值
     */
    init(operateType, obj){
      this.defaultValue.saveUpdSelect = operateType
      this.clearOldData()

      if (operateType === 'save'){
        this.defaultValue.title = '新增'

      } else if (operateType === 'upd'){
        this.defaultValue.title = '修改'
        // 要json处理下，否则会影响之前的值
        this.submitData = JSON.parse(JSON.stringify(obj))

        // 页面加载完成后执行，否则无法获取到dom
        this.$nextTick(() => {
          if (!checkNull(this.submitData.ico)){
            http.getImageUrl(this.submitData.ico).then(url => {
              this.$nextTick(() => {
                if (url) {
                  // 对图片回显进行处理，回显
                  let poster = {name: this.submitData.name, url: url, uid: this.submitData.id}
                  // 先清空，否则可能数据污染
                  this.$refs.componentRef.upload.fileList = []
                  this.$refs.componentRef.upload.fileList.push(poster)
                  this.$refs.componentRef.uploadHide()
                }
              })
            }).catch(e => {
              console.error('加载图片失败:', e)
            })

          }
        })

      } else {
        // 可能查看
      }

      this.tableConfig.show = true
    },
    /**
     * 清理掉旧数据
     */
    clearOldData(){
      this.submitData = {
        name: null,
        os: null,
        briefIntroduction: null,
        ico: null,
        officialWebUrl: null,
      }
    },
    /**
     * 是保存还是修改
     */
    toSaveUpd(){
      if (this.defaultValue.saveUpdSelect === 'save'){
        this.saveOpsComponent()

      } else if (this.defaultValue.saveUpdSelect === 'upd'){
        this.updOpsComponent()

      } else {

      }
    },
    /**
     * 保存
     */
    saveOpsComponent(){
      this.submitData.ico = this.$refs.componentRef.upload.fileId
      http.post("/opsComponent/saveOpsComponent", this.submitData).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }

        this.$message.success("保存成功");
        this.$emit('getOpsComponentPageList', null)
        // 关闭弹出框,继续添加
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 更新
     */
    updOpsComponent(){
      clearInvalid(this.submitData)
      if (!checkNull(this.$refs.componentRef.upload.fileId)){
        this.submitData.ico = this.$refs.componentRef.upload.fileId
      }
      http.post("/opsComponent/updOpsComponent", this.submitData).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }

        this.$message.success("更新成功");
        this.$emit('getOpsComponentPageList', null)
        // 关闭弹出框
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
  }
}
</script>

<style scoped>

</style>

